<template>
  <div class="user">
    <page-search
      :searchFormConfig="searchFormConfig"
      @resetBtnClick="handleResetBtn"
      @searchBtnClick="handleSearchBtn"
    ></page-search>
    <page-content
      ref="pageContentRef"
      :contentTableConfig="contentTableConfig"
      pageName="users"
      @createBtnClick="handleCreateData"
      @updateBtnClick="handleUpdateData"
    ></page-content>
    <page-modal
      ref="pageModalRef"
      pageName="users"
      :defaultInfo="defaultInfo"
      :modalConfig="modalConfigComputed"
    ></page-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue'

import { searchFormConfig } from './config/search-config'
import { contentTableConfig } from './config/content-config'
import { modalDialogConfig } from './config/modal-config'

import { usePageSearch } from '@/hooks/usePageSearch'
import { usePageModal } from '@/hooks/usePageModal'

import { useStore } from '@/store'
import { IFormType } from '@/base-ui/form'

export default defineComponent({
  name: 'user',
  setup() {
    // 1.重置和搜索按钮的hook
    const [pageContentRef, handleResetBtn, handleSearchBtn] = usePageSearch()

    // 3.动态添加部门和角色列表
    // modalConfig配置使用computed包裹
    const store = useStore()
    const modalConfigComputed = computed(() => {
      const departmentItem: IFormType | undefined =
        modalDialogConfig.formItems?.find(
          (item) => item.field === 'departmentId'
        )
      departmentItem!.options = store.state.entireDepartment.map(
        (item: any) => {
          return { title: item.name, value: item.id }
        }
      )
      const roleItem: IFormType | undefined = modalDialogConfig.formItems?.find(
        (item) => item.field === 'roleId'
      )
      roleItem!.options = store.state.entireRole.map((item: any) => {
        return { title: item.name, value: item.id }
      })
      return modalDialogConfig
    })

    // 2.添加和编辑按钮的hook
    const newCallback = () => {
      const passwordItem = modalConfigComputed.value.formItems?.find(
        (item) => item.field === 'password'
      )
      passwordItem!.isHidden = false
    }
    const editCallback = () => {
      const passwordItem = modalConfigComputed.value.formItems?.find(
        (item) => item.field === 'password'
      )
      passwordItem!.isHidden = true
    }
    const [pageModalRef, defaultInfo, handleCreateData, handleUpdateData] =
      usePageModal(newCallback, editCallback)

    return {
      searchFormConfig,
      contentTableConfig,
      modalConfigComputed,
      pageContentRef,
      pageModalRef,
      handleResetBtn,
      handleSearchBtn,
      handleCreateData,
      handleUpdateData,
      defaultInfo
    }
  }
})
</script>

<style scoped lang="less"></style>
